/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.dbswitch;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.table.ColumnType;
import com.je.common.base.constants.table.TableType;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.SQLFormatterUtil;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.model.database.ColumnDescription;
import com.je.meta.model.database.ImportedKeyData;
import com.je.meta.model.database.IndexesData;
import com.je.meta.model.database.SchemaTableMeta;
import com.je.meta.model.database.type.ImportedKeyTypeEnum;
import com.je.meta.model.database.type.ProductTypeEnum;
import com.je.meta.service.dbswitch.converter.IDateBaseConverterFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@RpcSchema(schemaId = "dbSwitchService")
public class DbSwitchRpcServiceImpl implements DbSwitchRpcService {

    private static final String[] SYS_CODES = new String[]{"SY_CREATEORGID", "SY_CREATEORGNAME", "SY_CREATETIME",
            "SY_CREATEUSERID", "SY_CREATEUSERNAME", "SY_MODIFYORGID", "SY_MODIFYORGNAME", "SY_MODIFYUSERID",
            "SY_MODIFYUSERNAME", "SY_MODIFYTIME", "SY_STARTEDUSER", "SY_STARTEDUSERNAME", "SY_APPROVEDUSERS",
            "SY_APPROVEDUSERNAMES", "SY_PREAPPROVUSERS", "SY_LASTFLOWINFO", "SY_PREAPPROVUSERNAMES", "SY_LASTFLOWUSER",
            "SY_LASTFLOWUSERID", "SY_WFWARN", "SY_WARNFLAG", "SY_CURRENTTASK", "SY_AUDFLAG", "SY_PIID", "SY_PDID",
            "SY_PRODUCT_ID", "SY_PRODUCT_CODE", "SY_PRODUCT_NAME", "SY_TENANT_ID", "SY_TENANT_NAME", "SY_ORG_ID", "SY_GROUP_COMPANY_NAME"
            , "SY_GROUP_COMPANY_ID", "SY_COMPANY_NAME", "SY_COMPANY_ID", "SY_ORDERINDEX", "SY_STATUS"};

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DynaCache dynaCache;

    @Override
    public void updateMetaDataTablesInfo(List<SchemaTableMeta> list, String syParent, String productId) {
        DynaBean product = metaService.selectOne("JE_PRODUCT_MANAGE", ConditionsWrapper.builder().
                eq("JE_PRODUCT_MANAGE_ID", productId));
        List<DynaBean> tables = new ArrayList<>();
        for (SchemaTableMeta schemaTableMeta : list) {
            DynaBean table = updateJeTableInfoMeta(schemaTableMeta, syParent, product);
            updateJeTableColumnsInfo(schemaTableMeta, table);
            updateJeTableKeysInfo(schemaTableMeta, table);
            updateJeTableIndexInfo(schemaTableMeta, table);
            metaService.update(table);
            tables.add(table);
        }
        //处理主子表信息
        for (DynaBean table : tables) {
            updateTableChildTableAndParentTable(table);
            tableCache.removeCache(table.getStr("RESOURCETABLE_TABLECODE"));
            dynaCache.removeCache(table.getStr("RESOURCETABLE_TABLECODE"));
        }
    }

    /**
     * 处理主子表信息
     *
     * @param table 表
     */
    public void updateTableChildTableAndParentTable(DynaBean table) {
        List<DynaBean> childList = metaService.select("JE_CORE_TABLEKEY", ConditionsWrapper.builder()
                .eq("TABLEKEY_TYPE", ImportedKeyTypeEnum.Foreign)
                .eq("TABLEKEY_LINKTABLE", table.getStr("RESOURCETABLE_TABLECODE")));
        List<String> childTableCodes = new ArrayList<>();
        List<String> parentTableCodes = new ArrayList<>();
        boolean isHaveChildTableOrParentTable = false;
        for (DynaBean dynaBean : childList) {
            childTableCodes.add(dynaBean.getStr("TABLEKEY_TABLECODE"));
        }
        String childTableCodesStr = StringUtils.join(childTableCodes.toArray(), ",");
        if (table.getStr("RESOURCETABLE_CHILDTABLECODES") == null || !table.getStr("RESOURCETABLE_CHILDTABLECODES").equals(childTableCodesStr)) {
            isHaveChildTableOrParentTable = true;
            table.set("RESOURCETABLE_CHILDTABLECODES", childTableCodesStr);
        }

        List<DynaBean> parentList = metaService.select("JE_CORE_TABLEKEY", ConditionsWrapper.builder()
                .eq("TABLEKEY_TYPE", ImportedKeyTypeEnum.Foreign)
                .eq("TABLEKEY_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE")));
        for (DynaBean dynaBean : parentList) {
            parentTableCodes.add(dynaBean.getStr("TABLEKEY_LINKTABLE"));
        }

        String parentTableCodesStr = StringUtils.join(parentTableCodes.toArray(), ",");
        if (table.getStr("RESOURCETABLE_PARENTTABLECODES") == null || !table.getStr("RESOURCETABLE_PARENTTABLECODES").equals(parentTableCodesStr)) {
            isHaveChildTableOrParentTable = true;
            //所属父表
            table.set("RESOURCETABLE_PARENTTABLECODES", parentTableCodesStr);
        }
        if (isHaveChildTableOrParentTable) {
            metaService.update(table);
        }
    }

    public DynaBean updateJeTableInfoMeta(SchemaTableMeta schemaTableMeta, String syParent, DynaBean product) {
        String tableName = schemaTableMeta.getTableCode();
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder()
                .eq("RESOURCETABLE_TABLECODE", tableName).eq("SY_PRODUCT_ID", product.getStr("JE_PRODUCT_MANAGE_ID")));
        boolean isInsert = false;
        if (table == null) {
            isInsert = true;
            table = new DynaBean("JE_CORE_RESOURCETABLE", true);
            String uuid = JEUUID.uuid();
            table.set("JE_CORE_RESOURCETABLE_ID", uuid);
            table.set("SY_PARENT", syParent);
            //普通表处理
            if (schemaTableMeta.getTableType().equals(TableType.PTTABLE)) {
                table.set("RESOURCETABLE_ICON", "jeicon jeicon-table");
                table.set("RESOURCETABLE_IMPORT", 1);
                table.set("RESOURCETABLE_TYPE", TableType.PTTABLE);
            } else {//视图处理
                table.set("RESOURCETABLE_ICON", "jeicon jeicon-process");
                table.set("RESOURCETABLE_IMPORT", 1);
                table.set("RESOURCETABLE_TYPE", TableType.VIEWTABLE);
                table.set("RESOURCETABLE_SQL", SQLFormatterUtil.format(schemaTableMeta.getCreateSql()).trim());
            }
            commonService.buildModelCreateInfo(table);
            commonService.buildResourceTable(table);
            if (StringUtil.isNotEmpty(table.getStr("SY_PATH"))) {
                table.set("SY_PATH", table.getStr("SY_PATH") + "/" + uuid);
            }
            table.set("RESOURCETABLE_ISCREATE", 1);
            table.set("SY_DISABLED", 0);
            table.set("SY_JECORE", "0");
            table.set("SY_JESYS", "0");
            table.set("RESOURCETABLE_MOREROOT", "0");
            table.set("RESOURCETABLE_USEFUNC", "0");
            table.set("RESOURCETABLE_IMPLWF", "0");
            table.set("RESOURCETABLE_OLDTABLECODE", schemaTableMeta.getTableCode());
            table.set("RESOURCETABLE_IMPLWF", "0");
            table.set("SY_PRODUCT_ID", product.getStr("JE_PRODUCT_MANAGE_ID"));
            table.set("SY_PRODUCT_NAME", product.getStr("PRODUCT_NAME"));
            table.set("SY_PRODUCT_CODE", product.getStr("PRODUCT_CODE"));
            table.set("RESOURCETABLE_TABLECODE", schemaTableMeta.getTableCode());
        }
        if (schemaTableMeta.getTableType().equals(TableType.VIEWTABLE)) {
            table.set("RESOURCETABLE_SQL", new SQLFormatterUtil().format(schemaTableMeta.getCreateSql()).trim());
        }
        //注解
        table.set("RESOURCETABLE_TABLENOTE", schemaTableMeta.getTableName());
        //备注
        table.set("RESOURCETABLE_REMARK", schemaTableMeta.getTableName());
        table.set("RESOURCETABLE_PKCODE", StringUtils.join(schemaTableMeta.getPrimaryKeys().toArray(), ","));
        //同步表结构时，不覆盖用户输入的表名称
        if(StringUtil.isEmpty(table.getStr("RESOURCETABLE_TABLENAME"))){
            if (Strings.isNullOrEmpty(schemaTableMeta.getTableName())) {
                table.set("RESOURCETABLE_TABLENAME", schemaTableMeta.getTableCode());
            } else {
                if(schemaTableMeta.getTableName().equals("VIEW")){//视图的备注默认是VIEW，不符合业务场景，这里做一下判断
                    table.set("RESOURCETABLE_TABLENAME", schemaTableMeta.getTableCode().toUpperCase());
                }else {
                    table.set("RESOURCETABLE_TABLENAME", schemaTableMeta.getTableName());
                }
            }
        }

        //设置主键生成策略
        buildTableKeyResourceTable(table, schemaTableMeta);
        if (isInsert) {
            metaService.insert(table);
        } else {
            commonService.buildModelModifyInfo(table);
            metaService.update(table);
        }
        return table;
    }

    private void buildTableKeyResourceTable(DynaBean table, SchemaTableMeta schemaTableMeta) {
        table.setStr("RESOURCETABLE_KEY_GENERATOR_NAME", schemaTableMeta.getKeyGeneratorName());
        table.setStr("RESOURCETABLE_KEY_GENERATOR_TYPE", schemaTableMeta.getKeyGeneratorType());
        table.setStr("RESOURCETABLE_KEY_GENERATOR_SQL", schemaTableMeta.getKeyGeneratorSql());
        table.setStr("RESOURCETABLE_INCREMENTER_NAME", schemaTableMeta.getIncrementerName());
    }

    /**
     * 修改表列信息
     *
     * @param schemaTableMeta 表元数据信息
     * @param table           meta资源表信息
     */
    public void updateJeTableColumnsInfo(SchemaTableMeta schemaTableMeta, DynaBean table) {
        int i = 1;
        List<ColumnDescription> list = schemaTableMeta.getColumns();
        //主键
        List<String> primaryKeys = schemaTableMeta.getPrimaryKeys();
        //外键
        List<ImportedKeyData> importedKeyDataList = schemaTableMeta.getImportedKeyData();
        Map<String, ImportedKeyData> importedKeyDataMap = new HashMap<>();
        for (ImportedKeyData importedKeyData : importedKeyDataList) {
            importedKeyDataMap.put(importedKeyData.getColumnCode(), importedKeyData);
        }
        List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder().
                eq("TABLECOLUMN_RESOURCETABLE_ID", table.getPkValue()));
        Map<String, DynaBean> columnMap = new HashMap<>();
        for (DynaBean dynaBean : columns) {
            columnMap.put(dynaBean.getStr("TABLECOLUMN_CODE"), dynaBean);
        }
        //先删除垃圾数据
        for (DynaBean dynaBean : columns) {
            boolean isIN = false;
            for (ColumnDescription columnDescription : list) {
                if (dynaBean.getStr("TABLECOLUMN_CODE").equals(columnDescription.getFieldName())) {
                    isIN = true;
                    break;
                }
            }
            if (!isIN) {
                metaService.delete("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder().eq("JE_CORE_TABLECOLUMN_ID", dynaBean.getPkValue()));
            }
        }

        for (ColumnDescription columnDescription : list) {
            DynaBean dynaBean;
            boolean isInsert = false;
            //不存在
            if (columnMap.get(columnDescription.getFieldName()) == null) {
                isInsert = true;
                dynaBean = new DynaBean("JE_CORE_TABLECOLUMN", true);
                dynaBean.setStr("TABLECOLUMN_RESOURCETABLE_ID", table.getPkValue());
                dynaBean.setStr("TABLECOLUMN_CODE", columnDescription.getFieldName());
                dynaBean.setStr("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
                dynaBean.setStr("TABLECOLUMN_NOTE", "");
                dynaBean.setStr("TABLECOLUMN_DEFAULTVALUE", "");
                dynaBean.setStr("TABLECOLUMN_TREETYPE", "");
                dynaBean.setStr("TABLECOLUMN_CHILDCONFIG", "");
                dynaBean.setStr("TABLECOLUMN_OLDUNIQUE", "0");
                dynaBean.setStr("TABLECOLUMN_VIEWCONFIG", "");
                dynaBean.setStr("TABLECOLUMN_DICCONFIG", "");
                dynaBean.setStr("TABLECOLUMN_DICQUERYFIELD", "");
                dynaBean.setStr("TABLECOLUMN_QUERYCONFIG", "");
                dynaBean.setStr("TABLECOLUMN_TREETYPE", "NORMAL");
                dynaBean.setStr("TABLECOLUMN_OLDCODE", columnDescription.getFieldName());
                dynaBean.setStr("TABLECOLUMN_SOURCE", "table");
            } else {
                dynaBean = columnMap.get(columnDescription.getFieldName());
            }
            dynaBean.setStr("TABLECOLUMN_CLASSIFY", Arrays.asList(SYS_CODES).contains(columnDescription.getFieldName()) ? "SYS" : "PRO");
            if (Strings.isNullOrEmpty(columnDescription.getRemarks())) {
                dynaBean.setStr("TABLECOLUMN_NAME", columnDescription.getFieldName());
            } else {
                dynaBean.setStr("TABLECOLUMN_NAME", columnDescription.getRemarks());
            }
            //设置字段类型和长度
            IDateBaseConverterFactory.getConverterByDBType(ProductTypeEnum.valueOf(columnDescription.getProductType().toString().toUpperCase()))
                    .buildTableColumnTypeAndLength(dynaBean, columnDescription);
            if (columnDescription.isNullable()) {
                dynaBean.setStr("TABLECOLUMN_ISNULL", "1");
            } else {
                dynaBean.setStr("TABLECOLUMN_ISNULL", "0");
            }
            dynaBean.setStr("TABLECOLUMN_UNIQUE", "0");
            dynaBean.setStr("TABLECOLUMN_OLDUNIQUE", "0");
            dynaBean.set("SY_ORDERINDEX", i);
            String type = columnDescription.getFieldTypeName();
            int precisionSize = columnDescription.getScaleSize();
            int length = columnDescription.getPrecisionSize();
            if (primaryKeys.contains(columnDescription.getFieldName())) {
                //是否唯一，唯一编码
                dynaBean.setStr("TABLECOLUMN_TYPE", ColumnType.ID);
                dynaBean.setStr("TABLECOLUMN_UNIQUE", "1");
                dynaBean.setStr("TABLECOLUMN_OLDUNIQUE", "1");
                dynaBean.set("SY_ORDERINDEX", "0");
                dynaBean.setStr("TABLECOLUMN_CLASSIFY", "SYS");
                i--;
                if (!type.startsWith(ColumnType.VARCHAR)) {
                    dynaBean.setStr("TABLECOLUMN_TYPE", ColumnType.CUSTOMID);
                    dynaBean.set("TABLECOLUMN_LENGTH", type + "(" + length + ")");
                }
            } else if (importedKeyDataMap.get(columnDescription.getFieldName()) != null) {
                if (dynaBean.getStr("TABLECOLUMN_TYPE").equals(ColumnType.VARCHAR50)) {
                    dynaBean.setStr("TABLECOLUMN_TYPE", ColumnType.FOREIGNKEY);
                }
                if (!type.startsWith(ColumnType.VARCHAR)) {
                    dynaBean.setStr("TABLECOLUMN_TYPE", ColumnType.CUSTOMFOREIGNKEY);
                    dynaBean.set("TABLECOLUMN_LENGTH", type + "(" + length + ")");
                }
            }
            dynaBean.setStr("TABLECOLUMN_ISCREATE", "1");
            i++;
            if (isInsert) {
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            } else {
                commonService.buildModelModifyInfo(dynaBean);
                metaService.update(dynaBean);
            }
        }
    }

    /**
     * 外键
     *
     * @param schemaTableMeta 表元数据信息
     * @param table           meta资源表信息
     */
    public void updateJeTableKeysInfo(SchemaTableMeta schemaTableMeta, DynaBean table) {
        int i = 0;
        List<ImportedKeyData> list = schemaTableMeta.getImportedKeyData();
        List<DynaBean> keys = metaService.select("JE_CORE_TABLEKEY", ConditionsWrapper.builder().
                eq("TABLEKEY_RESOURCETABLE_ID", table.getPkValue()));
        Map<String, DynaBean> keysMap = new HashMap<>();
        for (DynaBean dynaBean : keys) {
            keysMap.put(dynaBean.getStr("TABLEKEY_CODE"), dynaBean);
        }
        //先删除垃圾数据
        for (DynaBean dynaBean : keys) {
            boolean isIN = false;
            for (ImportedKeyData importedKeyData : list) {
                if (dynaBean.getStr("TABLEKEY_CODE").equals(importedKeyData.getKeyCode())) {
                    isIN = true;
                    break;
                }
            }
            if (!isIN) {
                metaService.delete("JE_CORE_TABLEKEY", ConditionsWrapper.builder().eq("JE_CORE_TABLEKEY_ID", dynaBean.getPkValue()));
            }
        }
        //主键也需要添加进去
        List<String> primaryKeys = schemaTableMeta.getPrimaryKeys();
        for (String primaryKey : primaryKeys) {
            DynaBean dynaBean = createNewImportedKey(table, primaryKey + "_CODE");
            dynaBean.setStr("TABLEKEY_TYPE", ImportedKeyTypeEnum.Primary.toString());
            dynaBean.setStr("TABLEKEY_COLUMNCODE", primaryKey);
            dynaBean.set("SY_ORDERINDEX", i);
            i++;
            commonService.buildModelCreateInfo(dynaBean);
            metaService.insert(dynaBean);
        }
        for (ImportedKeyData importedKeyData : list) {
            DynaBean dynaBean;
            boolean isInsert = false;
            //不存在
            if (keysMap.get(importedKeyData.getKeyCode()) == null) {
                isInsert = true;
                dynaBean = createNewImportedKey(table, importedKeyData.getKeyCode());
            } else {
                dynaBean = keysMap.get(importedKeyData.getKeyCode());
            }
            dynaBean.setStr("TABLEKEY_TYPE", importedKeyData.getType().toString());
            if (dynaBean.getStr("TABLEKEY_TYPE").equals(ImportedKeyTypeEnum.Inline.toString())) {
                dynaBean.set("TABLEKEY_ISRESTRAINT", "0");
            }
            dynaBean.setStr("TABLEKEY_COLUMNCODE", importedKeyData.getColumnCode());
            dynaBean.setStr("TABLEKEY_LINKTABLE", importedKeyData.getLinkTable());
            dynaBean.setStr("TABLEKEY_LINECOLUMNCODE", importedKeyData.getLineColumnCode());
            dynaBean.setStr("TABLEKEY_LINETYLE", importedKeyData.getCascadeType().getValue());
            dynaBean.set("SY_ORDERINDEX", i);
            i++;
            if (isInsert) {
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            } else {
                commonService.buildModelModifyInfo(dynaBean);
                metaService.update(dynaBean);
            }
        }
        if (list.size() > 0) {
            table.setStr("RESOURCETABLE_ISUSEFOREIGNKEY", "1");
        } else {
            table.setStr("RESOURCETABLE_ISUSEFOREIGNKEY", "0");
        }
    }

    private DynaBean createNewImportedKey(DynaBean table, String keyCode) {
        DynaBean dynaBean = new DynaBean("JE_CORE_TABLEKEY", true);
        dynaBean.setStr("TABLEKEY_RESOURCETABLE_ID", table.getPkValue());
        dynaBean.setStr("TABLEKEY_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        dynaBean.setStr("TABLEKEY_CODE", keyCode);
        dynaBean.set("SY_PRODUCT_ID", table.getStr("SY_PRODUCT_ID"));
        dynaBean.set("SY_PRODUCT_NAME", table.getStr("SY_PRODUCT_NAME"));
        dynaBean.set("SY_PRODUCT_CODE", table.getStr("SY_PRODUCT_CODE"));
        dynaBean.set("TABLEKEY_ISRESTRAINT", "1");
        dynaBean.set("TABLEKEY_ISCREATE", "1");
        return dynaBean;
    }

    public void updateJeTableIndexInfo(SchemaTableMeta schemaTableMeta, DynaBean table) {
        int i = 0;
        List<IndexesData> list = schemaTableMeta.getIndexesData();
        List<DynaBean> indexs = metaService.select("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().
                eq("TABLEINDEX_RESOURCETABLE_ID", table.getPkValue()));
        Map<String, String> cloumns = new HashMap<>();
        for (ColumnDescription columnDescription : schemaTableMeta.getColumns()) {
            if (Strings.isNullOrEmpty(columnDescription.getRemarks())) {
                cloumns.put(columnDescription.getFieldName(), columnDescription.getFieldName());
            } else {
                cloumns.put(columnDescription.getFieldName(), columnDescription.getRemarks());
            }
        }
        Map<String, DynaBean> indexMap = new HashMap<>();
        for (DynaBean dynaBean : indexs) {
            indexMap.put(dynaBean.getStr("TABLEINDEX_NAME"), dynaBean);
        }
        //先删除垃圾数据
        for (DynaBean dynaBean : indexs) {
            boolean isIN = false;
            for (IndexesData indexesData : list) {
                if (dynaBean.getStr("TABLEINDEX_NAME").equals(indexesData.getIndexName())) {
                    isIN = true;
                    break;
                }
            }
            if (!isIN) {
                metaService.delete("JE_CORE_TABLEINDEX", ConditionsWrapper.builder().eq("JE_CORE_TABLEINDEX_ID", dynaBean.getPkValue()));
            }
        }
        List<String> indexList = new ArrayList<>();
        for (IndexesData indexesData : list) {
            DynaBean dynaBean;
            boolean isInsert = false;
            //不存在
            if (indexMap.get(indexesData.getIndexName()) == null) {
                isInsert = true;
                dynaBean = createNewIndex(table, indexesData.getIndexName(), indexesData.getCode(), cloumns.get(indexesData.getCode()));
            } else {
                dynaBean = indexMap.get(indexesData.getIndexName());
                dynaBean.setStr("TABLEINDEX_FIELDNAME", cloumns.get(indexesData.getCode()));
            }
            dynaBean.setStr("TABLEINDEX_UNIQUE", indexesData.getUnique());
            dynaBean.setStr("TABLEINDEX_ISCREATE", "1");
            dynaBean.set("SY_ORDERINDEX", i);
            i++;
            if (isInsert) {
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            } else {
                commonService.buildModelModifyInfo(dynaBean);
                metaService.update(dynaBean);
            }
            indexList.add(indexesData.getCode());
        }

        //主键也需要添加进去
        List<String> primaryKeys = schemaTableMeta.getPrimaryKeys();
        for (String primaryKey : primaryKeys) {
            if(!indexList.contains(primaryKey)){
                String primaryKeyName = cloumns.get(primaryKey);
                DynaBean dynaBean = createNewIndex(table, "JE_" + UUID.randomUUID().toString() + "_ID", primaryKey, primaryKeyName);
                dynaBean.setStr("TABLEINDEX_UNIQUE", "1");
                dynaBean.set("SY_ORDERINDEX", i);
                i++;
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            }

        }
    }

    private DynaBean createNewIndex(DynaBean table, String indexName, String fieldCode, String fieldName) {
        DynaBean dynaBean = new DynaBean("JE_CORE_TABLEINDEX", true);
        dynaBean.setStr("TABLEINDEX_RESOURCETABLE_ID", table.getPkValue());
        dynaBean.setStr("TABLEINDEX_NAME", indexName);
        dynaBean.setStr("TABLEINDEX_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        dynaBean.set("SY_PRODUCT_ID", table.getStr("SY_PRODUCT_ID"));
        dynaBean.set("SY_PRODUCT_NAME", table.getStr("SY_PRODUCT_NAME"));
        dynaBean.set("SY_PRODUCT_CODE", table.getStr("SY_PRODUCT_CODE"));
        dynaBean.setStr("TABLEINDEX_FIELDCODE", fieldCode);
        dynaBean.setStr("TABLEINDEX_FIELDNAME", fieldName);
        dynaBean.setStr("TABLEINDEX_CLASSIFY", "PRO");
        dynaBean.setStr("TABLEINDEX_ISCREATE", "1");
        return dynaBean;
    }

}
